import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import moment from 'moment';
import { Table, Divider, Popconfirm, Icon, Form, InputNumber, Input  } from 'antd';
import styled from 'styled-components'
import SearchForm  from './components/SearchForm';
const MySpan = styled.span`
   color: #0880DF;
   &:hover{
     cursor: pointer;
   }

`
export interface Props {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  buttons?: Array<any>,
  list: {
    data: Array<any>,
    dataCnt: number
  }
}

const ONE_PAGE_SIZE = 10;


interface IContextProps {
  state: any;
  dispatch: ({ type }: { type: string }) => void;
}

const EditableContext = React.createContext({} as IContextProps);
class EditableCell extends Component<any, any> {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: dataIndex === 'name' ? true : false ,
                  message: `请输入 ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}








@connect(({ role, loading, menu }) => ({
  list: role.list || {},
  buttons: menu.buttons || [],
  loading: loading.effects['role/queryPage']
}))
class Role extends Component<any, any> {

  state = {
    current: 1,
    keyCount: 2,
    dataSource: [],
    editingKey: '' ,
    isDisable: false,
    subType: 0 , //0是添加   1是修改
    detailId: '',
  };

  queryData(offset = 1, size = ONE_PAGE_SIZE) {
    const { dispatch } = this.props;

    dispatch({
      type: 'role/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
      },
    }).then(() => {
        const { list } = this.props
        const { data=[] } = list
        const ans = data && Array.isArray(data) ? data.map((item, index) => ({
          key: index,
          id: item.id,
          idNum: index + 1 < 10 ? `0${index + 1}` : index + 1,
          name: item.name,
          createTime: item.createTime ? moment(item.createTime).format("YYYY-MM-DD") : "",
          remark: item.remark
          })
        ) : [];
        this.setState({
          dataSource: ans,
          isDisable: false,
          current: 1,
          editingKey: ''
        })
    })
  }

  initCurrent = () => {
    this.queryData()
  };

  remove = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/remove',
      payload: id
    }).then(() => {
      this.queryData();
    })
  };

  handleAuth(data) {
    const { dispatch } = this.props;

    dispatch({
      type: 'role/setInfo',
      payload: data
    })
  }

  componentDidMount() {
    this.queryData();
  }
  edit({key, id}, type=1) {
    this.setState({
       editingKey: key ,
       isDisable: true,
       subType: type,
       detailId : id,
      });
      
  }
  //添加input框
  handleAdd = () => {
    const { dataSource, keyCount } = this.state;

    const newData = {

      key: Date(),
      name: '',
      createTime: moment(Date()).format('YYYY-MM-DD'),
      remark: '',
    };
    this.setState(() => ( {
      dataSource: [newData, ...dataSource],
      count: keyCount + 1,
      isDisable: true
    }), () => {
      
        this.edit({key:newData.key}, 0)
    });
  };


  isEditing = record => record.key === this.state.editingKey;



 save(form, key){
  const { dispatch } = this.props
  form.validateFields((error, row) => {
    if(error){
      return;
    }
    
  this.state.subType === 0 ?  dispatch({
      type: 'role/create',
      payload: row
    }).then(() => {
      this.queryData()
    }) : dispatch({
      type: 'role/update',
      payload: {
        id: this.state.detailId,
        ...row,
      }
    }).then(() => {
      this.queryData()
    })
  })
 }
 cancel(key){
   this.queryData();
 }
  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    const { list, buttons } = this.props;
    const { data = [], dataCnt } = list;
    const btnList = {};

    buttons.forEach(item => {
      btnList[item.name] = item.name
    });
    
    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: ONE_PAGE_SIZE,
      onChange: (current) => {
        this.setState({ 
          current,
        })
        this.queryData(current)
      },
    };
    
    let columns = [
      {
        title: '序号',
        dataIndex: 'idNum',

      },
      {
        title: '角色名称',
        dataIndex: 'name',
        editable: true,
      }, 
      {
        title: '最后修改时间',
        dataIndex: 'createTime'
      },
       {
        title: '备注',
        dataIndex: 'remark',
        editable: true,
      },  {
        title: '操作', key: 'x', render: (record) => {
          const editable = this.isEditing(record);
          
        return editable ? 
        (
          <span>
          <EditableContext.Consumer>
            {form => (
              <a
                onClick={() => this.save(form, record.key)}
                style={{ marginRight: 8 }}
              >
                保存
              </a>
            )}
          </EditableContext.Consumer>
          <Popconfirm title="确定取消?" onConfirm={() => this.cancel(record.key)}>
            <a>取消</a>
          </Popconfirm>
        </span>
        )
        
       :(
          <div style={{display: 'flex'}}>
            {
              btnList['编辑'] ? <>
                <MySpan  onClick={this.edit.bind(this, record)}>编辑</MySpan>
                <Divider type="vertical" />
              </> : null
            }
            {
              btnList['权限配置'] ? <>
                <Link to={`/data/role/${record.id}/auth`} onClick={this.handleAuth.bind(this, record)}>权限配置</Link>
                <Divider type="vertical" />
              </> : null
            }
            {
              btnList['删除'] ? <>
                <Popconfirm 
                  title="请确认是否删除?" 
                  onConfirm={this.remove.bind(this, record.id)} 
                  okText="确定" 
                  cancelText="取消"
                  icon={<Icon type="exclamation-circle" />}
                >
                  <a>删除</a>
                </Popconfirm>
              </> : null
            }
          </div>
        )}
      }];

    let newColumns = columns.map(col => {
        if (!col.editable) {
          return col;
        }
        return {
          ...col,
          onCell: record => ({
            record,
            inputType: col.dataIndex === 'age' ? 'number' : 'text',
            dataIndex: col.dataIndex,
            title: col.title,
            editing: this.isEditing(record),
          }),
        };
      });
    return (
      <div>
      <EditableContext.Provider value={this.props.form}>

        <SearchForm isDisable={this.state.isDisable} add={this.handleAdd} current={ this.state.current } initCurrent={this.initCurrent} new={!!btnList['新增']}/>
        <Table
          columns={newColumns}
          pagination={ pagination }
          dataSource={this.state.dataSource}
          loading={this.props.loading}
          bordered
          components={components}
        />
      </EditableContext.Provider>

      </div>
    );
  }
}
const EditableFormTable = Form.create()(Role);

export default EditableFormTable;
